package login;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import web.HttpClientFactory;

public class Login{
	//登陆
	public static boolean login(String userName, String passWord) {
		// TODO Auto-generated method stub
		String httpUrl = "http://bbs.dlut.edu.cn/nforum/m/user/login";
		HttpPost httppost = new HttpPost(httpUrl);
		HttpClient client = HttpClientFactory.getHttpClient();
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id",userName));
		params.add(new BasicNameValuePair("passwd",passWord));
		try{
			HttpEntity httpentity = new UrlEncodedFormEntity(params,"gb2312");
			httppost.setEntity(httpentity);
			HttpResponse httpResponse = client.execute(httppost);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if(statusCode == HttpStatus.SC_MOVED_TEMPORARILY){
				return true;
			}else
				return false;
		}catch(Exception e){
			return false;
		}
		
	}

	//注销
	public static boolean logout() {
		// TODO Auto-generated method stub
		if(isLogin()){
			String httpUrl ="http://bbs.dlut.edu.cn/nforum/m/user/logout";
			HttpGet httpget = new HttpGet(httpUrl);
			try{
				HttpClient client = HttpClientFactory.getHttpClient();
				HttpResponse httpResponse = client.execute(httpget);
				int statusCode = httpResponse.getStatusLine().getStatusCode();
				if(statusCode == HttpStatus.SC_MOVED_TEMPORARILY){
					return true;
				}else
					return false;
			}catch(Exception e){
				return false;
			}
		}
		return true;
	}

	//是否登录
	public static boolean isLogin() {
		// TODO Auto-generated method stub
		DefaultHttpClient client = (DefaultHttpClient)HttpClientFactory.getHttpClient();
		List<Cookie> cookies = client.getCookieStore().getCookies();
		if(cookies!=null){
			for(Cookie c:cookies){
				if(c.getName().equals("nforum[UTMPUSERID]")&&!c.getValue().equals("guest"))
					return true;
			}
		}
		return false;
	}
}
